import { getUserInfo, login, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'

const useUserStore = defineStore(
'user',
{
  state: () => ({
    token: getToken(),
    name: undefined,
    userId: undefined,
    grade: undefined,
    phone: undefined,
    openId: undefined,
    schoolName:undefined,//改字段不是指驾校，是一个无用字段，暂时用来确定获取pc注册码权限
  }),
  actions: {
    // 登录
    login(userInfo) {
      const mobile = userInfo.mobile.trim()
      const code = userInfo.code.trim()
      return new Promise((resolve, reject) => {
        login(mobile, code).then((res) => {
          setToken(res.data.access_token)
          this.token = res.data.access_token
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          const user = res.data
          this.name = user.name
          this.userId = user.id
          this.grade = user.grade
          this.schoolName = user.schoolname
          this.phone = user.phone
          this.openId = user.weixinid
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 退出系统
    logout() {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          this.token = ''
          this.userId = ''
          removeToken()
          resolve(null)
        }).catch((error) => {
          reject(error)
        })
      })
    }
  }
})
export default useUserStore

